<template>
  <div class="ad-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>广告管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleAdd">新增广告</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="广告名称">
          <el-input v-model="searchForm.name" placeholder="请输入广告名称"></el-input>
        </el-form-item>
        <el-form-item label="广告位置">
          <el-select v-model="searchForm.position" placeholder="请选择广告位置">
            <el-option label="首页轮播" value="home_banner"></el-option>
            <el-option label="商品详情" value="product_detail"></el-option>
            <el-option label="分类页" value="category"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="广告名称"></el-table-column>
        <el-table-column prop="position" label="广告位置">
          <template slot-scope="scope">
            {{ getPositionText(scope.row.position) }}
          </template>
        </el-table-column>
        <el-table-column prop="image" label="广告图片">
          <template slot-scope="scope">
            <el-image 
              style="width: 100px; height: 60px"
              :src="scope.row.image"
              fit="cover">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="link" label="链接地址"></el-table-column>
        <el-table-column prop="sort" label="排序" width="80"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="广告名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="广告位置" prop="position">
          <el-select v-model="form.position" placeholder="请选择广告位置">
            <el-option label="首页轮播" value="home_banner"></el-option>
            <el-option label="商品详情" value="product_detail"></el-option>
            <el-option label="分类页" value="category"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接地址" prop="link">
          <el-input v-model="form.link"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AdIndex',
  data() {
    return {
      searchForm: {
        name: '',
        position: '',
        status: ''
      },
      tableData: [],
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增广告',
      form: {
        id: '',
        name: '',
        position: '',
        image: '',
        link: '',
        sort: 0,
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入广告名称', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请选择广告位置', trigger: 'change' }
        ],
        image: [
          { required: true, message: '请上传广告图片', trigger: 'change' }
        ],
        link: [
          { required: true, message: '请输入链接地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取广告列表
    async getAdList() {
      try {
        const res = await this.$http.get('/api/ad/list', {
          params: {
            ...this.searchForm,
            page: this.page.current,
            size: this.page.size
          }
        })
        this.tableData = res.data.list
        this.page.total = res.data.total
      } catch (error) {
        this.$message.error('获取广告列表失败')
      }
    },
    // 搜索
    handleSearch() {
      this.page.current = 1
      this.getAdList()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        position: '',
        status: ''
      }
      this.handleSearch()
    },
    // 新增广告
    handleAdd() {
      this.dialogTitle = '新增广告'
      this.form = {
        id: '',
        name: '',
        position: '',
        image: '',
        link: '',
        sort: 0,
        status: 1
      }
      this.dialogVisible = true
    },
    // 编辑广告
    handleEdit(row) {
      this.dialogTitle = '编辑广告'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除广告
    handleDelete(row) {
      this.$confirm('确认删除该广告吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$http.delete(`/api/ad/${row.id}`)
          this.$message.success('删除成功')
          this.getAdList()
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },
    // 修改状态
    async handleStatusChange(row) {
      try {
        await this.$http.put(`/api/ad/${row.id}/status`, {
          status: row.status
        })
        this.$message.success('状态修改成功')
      } catch (error) {
        row.status = row.status === 1 ? 0 : 1
        this.$message.error('状态修改失败')
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            if (this.form.id) {
              await this.$http.put(`/api/ad/${this.form.id}`, this.form)
            } else {
              await this.$http.post('/api/ad', this.form)
            }
            this.$message.success('保存成功')
            this.dialogVisible = false
            this.getAdList()
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    },
    // 图片上传成功
    handleImageSuccess(res) {
      this.form.image = res.data.url
    },
    // 图片上传前校验
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    // 获取广告位置文本
    getPositionText(position) {
      const positionMap = {
        'home_banner': '首页轮播',
        'product_detail': '商品详情',
        'category': '分类页'
      }
      return positionMap[position] || position
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.page.size = val
      this.getAdList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.page.current = val
      this.getAdList()
    }
  },
  created() {
    this.getAdList()
  }
}
</script>

<style scoped>
.ad-container {
  padding: 20px;
}
.search-form {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
